I need a query to retrieve records from the Sales table for the last 7 days. Can someone provide the SQL query for this?
home / developersection / forums / how to write a query to get data from the last 7 days in sql server?
I need a query to retrieve records from the Sales table for the last 7 days. Can someone provide the SQL query for this?
Ravi Vishwakarma
16-Jul-2024To retrieve data from the last 7 days in SQL Server, you can use the
GETDATE()function along with theDATEADD()function to filter the rows.Here's a simple example of how to achieve this:
Assume you have a table named
Userswith a columnCreationDatethat stores the date and time when each order was placed.Query to Get Data from the Last 7 Days
Explanation
GETDATE(): This function returns the current date and time.DATEADD(day, -7, GETDATE()): This function subtracts 7 days from the current date and time. It essentially calculates the date and time exactly 7 days ago.OrderDate >= DATEADD(day, -7, GETDATE()): This condition filters the rows to include only those where theCreationDateis within the last 7 days.